package com.jingjing.control.user;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.jingjing.model.user.LoginUser;
import com.jingjing.model.user.User;
import com.jingjing.service.common.CommonService;
import com.jingjing.service.user.LoginUserService;
import com.jingjing.service.user.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @program: jingjing
 * @description: 用户相关操作
 * @author: 何伟
 * @create: 2019-03-13 18:58
 **/
@Controller
public class UserController {

    Logger logger= LoggerFactory.getLogger(this.getClass());

    @Value("${server.servlet.session.timeout}")
    private int timeout;
    @Autowired
    UserService userService;
    @Autowired
    LoginUserService loginUserService;
    @Autowired
    CommonService commonService;


    @RequestMapping("doLogin")
    @ResponseBody
    public String doLogin(String name, String pwd, HttpSession session, HttpServletRequest request) throws Exception{
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-mm-dd HH:mm:ss");
        Map loginMsg=new HashMap<String,String>();
        ObjectMapper mapper=new ObjectMapper();
        User sessionUser=null;
        User user=null;
        List<LoginUser> loginUsers=null;
//        1.判断当前登录用户
        if (null!=session){
            sessionUser=(User)session.getAttribute("user");
        }
//        2.当前用户是否存在
        user=userService.getUserByName(name);
        if (null==user){
            loginMsg.put("login","faild");
            loginMsg.put("信息提示","用户不存在！");
        }else{
//        3.当前登录用户已登录数量，可以同时在两个客户端登录
            loginUsers=loginUserService.getLoginUser(user.getId());
            if (loginUsers.size()>=2){
                loginMsg.put("login","faild");
                loginMsg.put("信息提示","您已登录,一个账户最多可登录两个客户端");
                return mapper.writeValueAsString(loginMsg);
            }else if (!pwd.equals(user.getPwd())){
                loginMsg.put("login","faild");
                loginMsg.put("信息提示","密码不正确");
            }else if (null!=sessionUser&&sessionUser.getName().equals(name)){
                loginMsg.put("login","faild");
                loginMsg.put("信息提示","您已在此窗口登录，可打开新的浏览器窗口登录！");
            }else{

                Date date=new Date();
                LoginUser loginUser=new LoginUser();
                loginUser.setUserId(user.getId());
                loginUser.setLoginTime(date);
//                loginUser.setIp(request.getRemoteHost());
                loginUser.setIp(commonService.getRemoteIP(request));
                loginUser.setPort(request.getRemotePort());
                loginUserService.addLoginUser(loginUser);

                session.setAttribute("loginTime",date);
                session.setAttribute("user",user);
                session.setMaxInactiveInterval(timeout);

                loginMsg.put("username",user.getName());
                loginMsg.put("logintime",sdf.format(date));
                loginMsg.put("timeout",timeout);
                loginMsg.put("login","success");
                logger.info("用户："+user.getName()+" 登录成功，登录时间："+sdf.format(date)+",会话时长为："+timeout);
            }
        }

        return mapper.writeValueAsString(loginMsg);
    }

    @RequestMapping("doRegist")
    @ResponseBody
    public String doRegist(@RequestBody @Validated User user, BindingResult result,HttpSession session) throws Exception {
        User sessionuser=null;
        ObjectMapper mapper=new ObjectMapper();
        Map<String,String> errMsg=new HashMap<>();

        if (null!=session){
            sessionuser=(User)session.getAttribute("user");
            if (null!=sessionuser){
                errMsg.put("validate","error");
                errMsg.put("提示","当前已登录！");
                return mapper.writeValueAsString(errMsg);
            }
        }


        if (result.hasErrors()){
            errMsg.put("validate","error");
            List<ObjectError> errorList=result.getAllErrors();
            for (ObjectError e: errorList) {
                FieldError fieldError=(FieldError)e;
                logger.info("验证信息 >>>>>>>>>>>>>>>>>>> "+"参数: "+ fieldError.getField()+" | 信息: "+ e.getDefaultMessage());
                errMsg.put(fieldError.getField(),e.getDefaultMessage());
            }

        }else{
//            errMsg.append("valied:success,");
            int count = userService.addUser(user);
            if (count==-1){
                errMsg.put("validate","error");
                errMsg.put("用户信息","用户名已存在！");
            }else{
                errMsg.put("validate","success");
            }
        }
        logger.info(mapper.writeValueAsString(errMsg));
        return mapper.writeValueAsString(errMsg);
//        return errMsg;
    }

    @RequestMapping("logout")
    public String logOut(HttpSession session){
        User u=null;
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if (null!=session) u=(User)session.getAttribute("user");
        if (null!=u){
            Date date=(Date)session.getAttribute("loginTime");
            loginUserService.removeLoginUser(u.getId(),date);
            session.removeAttribute("user");
        }
        session.invalidate();
        return "login";
    }

    @RequestMapping("userUnit")
    public String userUnit(HttpSession session, Model model){
        model.addAttribute("user",(User)session.getAttribute("user"));
        return "user-unit";
    }

//  session是否过期
    @RequestMapping("checkSession")
    @ResponseBody
    public Map checkSession(HttpServletRequest request){
        HttpSession session=request.getSession(false);
        Map sessionMap=new HashMap<String,String>();
        if (null==session){
            sessionMap.put("timeout","true");
        }else {
            sessionMap.put("timeout","false");
        }
        return sessionMap;
    }

}
